<template>
  <!-- 休息时间段表单弹窗 -->
  <el-dialog
    v-model="visibleDialog"
    :title="props.title"
    width="50%"
    draggable
    @close="closeDialog"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="100"
      v-show="!props.isReadonly"
    >
      <el-row>
        <el-col :span="24">
          <el-form-item label="休息日期" prop="restTimeSearch">
            <el-date-picker
              v-model="formData.restTimeSearch"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
              @change="getRestTimeStart"
              :disabled-date="disabledDate"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-card shadow="never" class="table-container">
      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
        style="height: 443px"
      >
        <el-table-column type="index" key="index" label="序号" width="55" align="center" />
        <el-table-column
          label="休息开始日期"
          prop="restTimeStart"
          min-width="120"
          show-overflow-tooltip
          align="center"
        >
          <template #default="{ row }">
            {{ row.restTimeStart.split(" ")[0] }}
          </template>
        </el-table-column>
        <el-table-column
          label="休息结束日期"
          prop="restTimeEnd"
          min-width="120"
          show-overflow-tooltip
          align="center"
        >
          <template #default="{ row }">
            {{ row.restTimeEnd.split(" ")[0] }}
          </template>
        </el-table-column>
        <el-table-column
          label="设置时间"
          prop="lastUpdateTime"
          min-width="160"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="设置人"
          prop="lastUpdatedUserName"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column fixed="right" label="操作" width="110" align="center">
          <template #default="scope">
            <el-button
              type="danger"
              size="small"
              link
              @click="deleteItem(scope.row.id)"
              ><i-ep-delete />删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>
    <template #footer>
      <div class="dialog-footer">
        <el-button
          v-if="!props.isReadonly"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
          >确 定</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
import { useTable, useDownload, useDictionary } from "@/utils/useTable";
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "MESMESRESTPERIODADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    if (newVal) {
      getTableList();
    }
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);

const rules = reactive({
  restTimeStart: [],
  restTimeEnd: [],
  restTimeSearch:[{required: true, message: "请选择休息日期", trigger: "change"}]
});

const formRef = ref(ElForm);

let formData = reactive({
  id: "",
  restTimeStart: "",
  restTimeEnd: "",
  version: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: "",
  deleted: "",
  restTimeSearch: [],
});

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
  reset();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.restTimeStart = "";
  formData.restTimeEnd = "";
  formData.version = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.enabled = "";
  formData.deleted = "";
  formData.restTimeSearch = [];
}

const loading = ref(false);

/** 休息时间段保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: "/mes/mesrestperiod/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}

// 是否需要分页
const pagination = true;
// 请求参数
const requestApi = "/mes/mesrestperiod/queryByPage";
// 表格操作 Hooks
const {
  tableData,
  pageable,
  getTableList,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  reset,
}: any = useTable(requestApi, pagination);
// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});
function getRestTimeStart(data: any) {
  if (data) {
    formData.restTimeStart = data[0];
    formData.restTimeEnd = data[1];
  } else {
    formData.restTimeStart = "";
    formData.restTimeEnd = "";
  }
}
const disabledDate = (time: Date) => {
  return time.getTime() <= Date.now();
};
async function deleteItem(id: any) {
  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const { data } = await request({
      url: `/mes/mesrestperiod/deleteItem/${id}`,
      method: "post",
    }).then((res) => {
      if (res.code == 200) {
        ElMessage.success("删除成功！");
      }
      getTableList();
    });
  });
}
</script>
